#include "cbasemodule.h"
#include "ui_cbasemodule.h"

#include <QFileDialog>

#include "cfam.h"

CBaseModule::CBaseModule(QWidget *parent) :
    QDockWidget(parent),
    ui(new Ui::CBaseModule)
{
    ui->setupUi(this);
}

CBaseModule::~CBaseModule()
{
    if( NULL != l_boot )
    {
        delete l_boot;
    }

    delete ui;
}

CBaseModule::CBaseModule(int id, QString addr, QWidget *parent) :
    QDockWidget(parent),
    ui(new Ui::CBaseModule)
{
    ui->setupUi(this);

    this->id = id;
    this->addr = addr;
    this->parent = parent;
    this->l_boot = NULL;

    setWindowTitle(addr);
}

int CBaseModule::GetId( void )
{
    return this->id;
}

void CBaseModule::AddMsg( QList<unsigned char> *ip_msg )
{
    // on va orienter en fonction de la famille
    switch( ip_msg->value(4) )
    {
        case E_FAM_NONE:
        {
            FamNoneMsg(ip_msg);
        }
        break;
        case E_FAM_GENERAL_ID:
        {
            FamGeneralMsg(ip_msg);
        }
        break;
    }
}

void CBaseModule::FamNoneMsg( QList<unsigned char> *ip_msg )
{
    // si on est en bootload on redirige
    if( NULL != l_boot )
    {
        l_boot->inRfMsg( ip_msg );
    }
    else
    {
        // en fonction des commandes
        switch( ip_msg->value(5) )
        {
            case FAM_NONE_CMD_ACK_ID:
            {
                // test payload
                if( FAM_NONE_CMD_ACK_PAYLOAD_SIZE == ip_msg->value(6) )
                {
                }
            }
            break;
        }
    }
}

void CBaseModule::FamGeneralMsg( QList<unsigned char> *ip_msg )
{
    // en fonction des commandes
    switch( ip_msg->value(5) )
    {
        case FAM_GEN_CMD_HB_ID:
        {
            // test payload
            if( FAM_GEN_CMD_HB_PAYLOAD_SIZE == ip_msg->value(6) )
            {
                // met a jour le bargraph
                int lc_value = 0xAF - ip_msg->value(7);
                ui->BarBatt->setValue(lc_value);
            }
        }
        break;
    }
}

void CBaseModule::on_BtnBootload_clicked()
{
    // demande le nom du fichier
    QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"),
                                                     "",
                                                     tr("Firmware (*.hex)"));
    if( "" != fileName )
    {
        // lance la fenetre de bootload pour le module
        l_boot = new Cbootloader( this->addr, fileName, this->parent );
        l_boot->show();
    }
}
